var user = [];
var chat = {
    'host'  :   'http://192.168.0.120',
    'port'  :   '7001',
    'my'    :   {
        'uid'   :   0,
        'nick'  :   'self'
    },
    'last_message_time' : 0,
    'who' : function(){
        $.ajax({ cache: false
               , type: "GET"
               , dataType: "json"
               , url: chat.host + ":" + chat.port + "/who?jsoncallback=?"
               , jsonp: 'jsoncallback'
               , error: function (jqXHR, textStatus, errorThrown) {
                   alert('error:'+textStatus);
                   return false;
                 }
               , success: function (sessions) {
                      if (sessions.error) {
                          //TODO
                      }else{
                          var selected_uid = [];
                          $("input[name='uid']:checked").each(function(i, item){
                              selected_uid[i] = $(item).val();
                          });
                          user = [];
                          user[0] = "所有人";
                          $("#user_list").empty();
                          $("#user_list").append("<label for='uid_0'><input type='checkbox' name='uid' value='0' id='uid_0'>全部</label>");
                          $.each(sessions, function(i, item){
                              if(item.uid != chat.my.uid){
                                  user[item.uid] = item.nick;
                                  $("#user_list").append("<label for='uid_"+item.uid+"'><input type='checkbox' name='uid' value='"+item.uid+"' id='uid_"+item.uid+"' >"+item.nick+"</label>");
                              }else{
                                  user[item.uid] = '我';
                              }
                          });
                          $.each(selected_uid, function(i, item){
                              if($("input[name='uid'][value='"+item+"']").length > 0){
                                  $("input[name='uid'][value='"+item+"']").attr('checked', 'checked');
                              }
                          });
                      }
                    }
               });
    },
    'join' : function(uid, nick, callback){
        nick = filter.encode(nick);
        $.ajax({ cache: false
               , type: "GET"
               , dataType: "json"
               , url: chat.host + ":" + chat.port + "/join?jsoncallback=?"
               , data:{uid : uid, nick : nick}
               , jsonp: 'jsoncallback'
               , error: function (jqXHR, textStatus, errorThrown) {
                   alert('error:'+textStatus);
                   return false;
                 }
               , success: function (session) {
                      if (session.error) {
                          //TODO
                      }else{
                          chat.my.nick = session.nick;
                          chat.my.uid  = session.uid;
                          chat.last_message_time   = chat.getTime();
                          chat.longPoll();
                      }
                      if(typeof(callback) == 'function'){
                          callback(session);
                      }
                    }
               });
               return false;
    },
    'longPoll' : function(data){
        if (data && data.messages) {
            if(typeof(data.messages.type)){
                    var message = data.messages;
                    if (message.timestamp > chat.last_message_time){
                        chat.last_message_time = message.timestamp;
                    }
                    switch (message.type) {
                        case "msg":
                          chat.addMessage(message.from_uid, message.to_uid, message.text, message.timestamp);
                          break;
                        case "join":
                          //chat.addMessage(message.from_uid, "", message.from_uid + "加入了", message.timestamp);
                          chat.who();
                          break;
                        case "part":
                          //chat.addMessage(0, "", message.nick + "离开了", message.timestamp);
                          chat.who();
                          break;
                    }
            }else{
                for (var i = 0; i < data.messages.length; i++) {
                    var message = data.messages[i];
                    if (message.timestamp > chat.last_message_time){
                        chat.last_message_time = message.timestamp;
                    }
                    switch (message.type) {
                        case "msg":
                          chat.addMessage(message.uid, message.nick, message.text, message.timestamp);
                          break;
                        case "join":
                          //chat.addMessage(message.from_uid, "", message.from_uid + "加入了", message.timestamp);
                          //chat.who();
                          break;
                        case "part":
                          //chat.addMessage(0, "", message.nick + "离开了", message.timestamp);
                          break;
                    }
                }
            }
                
        }
        $.ajax({ cache: false
            , type: "GET"
            , url: chat.host + ":" + chat.port + "/recv?jsoncallback=?"
            , dataType: "json"
            , jsonp : 'jsoncallback'
            , data: { since: chat.last_message_time, uid: chat.my.uid }
            , error: function (jqXHR, textStatus, errorThrown) {
                       alert('error:'+jqXHR.error());
                       return false;
                     }
            , success: function (data) {
                //transmission_errors = 0;
                chat.longPoll(data);
            }
         });
    },
    'send' : function(message){
        message = message.replace("\n", "");
        message = filter.encode(message);
        if(message){
            $.ajax({ cache: false
                   , type: "GET"
                   , dataType: "json"
                   , url: chat.host + ":" + chat.port + "/send?jsoncallback=?"
                   , data:{from_uid : chat.my.uid, to_uid : chat.getUid(), message : message}
                   , jsonp: 'jsoncallback'
                   , error: function (jqXHR, textStatus, errorThrown) {
                       alert('error:'+textStatus);
                       return false;
                     }
                   , success: function (data) {
                          if (data.error) {
                            alert("错误提示: " + data.error);
                            return;
                          }
                        }
                   });
        }
    },
    'addMessage' : function(from_uid, to_uid, text, time){
        if (text === null){
            return;
        }
        if (time == null) {
            time = new Date();
        } else if ((time instanceof Date) === false) {
            time = new Date(time);
        }
        var content = '<tr>'
              + '  <td class="date">' + user[from_uid] + '说</td>'
              + '  <td class="nick">' + filter.decode(text) + '</td>'
              + '  <td class="msg-text">' + util.timeString(time)  + '</td>'
              + '</tr>'
              ;

        $("#msg_list").append(content);
    },
    'quit' : function(){
        $.ajax({ cache: false
           , type: "GET"
           , dataType: "json"
           , url: chat.host + ":" + chat.port + "/part?jsoncallback=?"
           , data:{uid : chat.my.uid}
           , jsonp: 'jsoncallback'
           , error: function (jqXHR, textStatus, errorThrown) {
               alert('error:'+textStatus);
               return false;
             }
           });
    },
    'getTime' : function(){
        return Math.floor(new Date().getTime() / 1000);
    },
    'getUid' : function(){
        var select_uid = [];
        $("input[name='uid']:checked").each(function(i, item){
            if($(item).val() == '0'){
                return;
            }
            select_uid.push($(item).val());
        });
        if(select_uid.length == 0){
            return 0;
        }else{
            return select_uid.join(',');
        }
    }
    
}
var util = {
    zeroPad: function (digits, n) {
        n = n.toString();
        while (n.length < digits){
            n = '0' + n;
        }
        return n;
    },
    timeString: function (date) {
        var minutes = date.getMinutes().toString();
        var hours = date.getHours().toString();
        return this.zeroPad(2, hours) + ":" + this.zeroPad(2, minutes);
    }
}
var filter = {
    'encode' : function(text){
        text = $.trim(text);
        //text = encodeURI(text);
        return text;
    },
    'decode' : function(text){
        //return decodeURI(text);
        return text;
    }
}
$(window).unload(function () {
    chat.quit();
});
